<template>
  <el-dialog
    :model-value="dialogModify"
    width="40%"
    title="空间详情-编辑"
    :before-close="handleClose"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
    destroy-on-close
  >
    <div v-loading="loading" element-loading-text="加载中...">
      <el-divider class="custom-divider" />

      <!-- 编辑表单内容 -->
      <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
        <el-form-item label="空间名称：" prop="name">
          <div class="space-info-row">
            <SearchInput
              ref="searchInputRef"
              v-model="form.name"
              style="width: 470px"
              placeholder="请输入空间名称"
              :search-api="searchSpaces"
              @select="handleSpaceSelect"
              :search-data="newResponse"
              :disabled="disabledInput"
              @input="handleNameInput"
            />
            <CitySelect
              v-model="form.city"
              style="width: 180px"
              @change="handleCityChange"
              @cityValue="handleCityValue"
            />
          </div>
        </el-form-item>
        <el-form-item label="空间地址：" prop="destName">
          <el-input
            v-model="form.destName"
            disabled
            placeholder="选择空间名称后自动填入"
          />
        </el-form-item>
        <el-form-item label="地点坐标：" prop="destLongitude">
          <el-input
            :model-value="coordinates"
            disabled
            placeholder="选择空间名称后自动填入"
          />
        </el-form-item>

        <el-form-item label="封面图片：" prop="coverUrl">
          <el-upload
            class="upload-box"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleCoverChange"
            :on-remove="handleCoverRemove"
            accept="image/jpeg,image/png,image/gif,image/jpg"
          >
            <template v-if="form.coverUrl">
              <img :src="form.coverUrl" class="preview-image" />
              <div class="delete-icon" @click.stop="handleCoverRemove">
                <el-icon><Delete /></el-icon>
              </div>
            </template>
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <span>点击上传</span>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="空间平面：" prop="floorPlanUrl">
          <el-upload
            class="upload-box"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFloorPlanChange"
            :on-remove="handleFloorRemove"
            accept="image/jpeg,image/png,image/gif,image/jpg"
          >
            <template v-if="form.floorPlanUrl">
              <img :src="form.floorPlanUrl" class="preview-image" />
              <div class="delete-icon" @click.stop="handleFloorRemove">
                <el-icon><Delete /></el-icon>
              </div>
            </template>
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <span>点击上传</span>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="空间介绍：" prop="intro">
          <el-input
            v-model="form.intro"
            type="textarea"
            :rows="4"
            placeholder="请输入空间介绍"
          />
        </el-form-item>

        <el-form-item label="排序：" prop="orderLevel">
          <el-input-number
            v-model="form.orderLevel"
            :min="0"
            :precision="2"
            controls-position="right"
          />
          <span style="color: #909399; font-size: 12px; margin-left: 15px">
            数值越大，排序越靠前
          </span>
        </el-form-item>

        <el-form-item label="设施：" prop="facilityIdList">
          <el-select
            v-model="form.facilityIdList"
            placeholder="请选择"
            style="width: 240px"
            multiple
          >
            <el-option
              v-for="item in facilitiesListAll"
              :key="item.facilityId"
              :label="item.name"
              :value="item.facilityId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="视频：" prop="mediaIdList">
          <el-select
            v-model="form.mediaIdList"
            placeholder="请选择"
            style="width: 240px"
            multiple
          >
            <el-option
              v-for="item in videoListAll"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="活动公告：" prop="todayAnnouncement">
          <el-input
            v-model="form.todayAnnouncement"
            type="textarea"
            :rows="4"
            placeholder="请输入活动公告"
          />
        </el-form-item>

        <!-- 二维码信息 -->
        <el-form-item label="加入二维码：">
          <div class="qrcode-wrapper">
            <div class="qrcode-header">
              <el-button
                type="primary"
                link
                size="small"
                @click="handleAddQrcode"
              >
                添加
              </el-button>
            </div>
            <div class="qrcode-section">
              <el-table
                :data="qrcodeData"
                style="width: 100%"
                border
                stripe
                fit
                empty-text="暂无数据"
                show-header
                size="small"
                element-loading-text="Loading..."
                :header-cell-style="{ background: '#e7e1fb' }"
                max-height="200px"
              >
                <el-table-column prop="codeTitle" label="底部文字信息" />
                <el-table-column prop="url" label="二维码图片">
                  <template #default="scope">
                    <template v-if="scope.row.url">
                      <el-image
                        :src="scope.row.url"
                        fit="cover"
                        style="width: 50px; height: 50px"
                      />
                    </template>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="state" label="详情">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="handleQrcodeEdit(scope.row)"
                      size="small"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="handleQrcodeDelete(scope.row)"
                      size="small"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态：" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :value="0">展示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <QrcodeEdit_Dialog
    v-model:visible="qrcodeDialogVisible"
    :edit-data="currentEditData"
    :is-edit="isEdit"
    @confirm="handleQrcodeConfirm"
  />
</template>

<script setup name="ModifySpaceDialog">
import { ref, computed, nextTick } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue';
import {
  getAddress,
  getFacilities,
  getVideoList,
  modifySpace,
  getSpaceDetails,
} from '@/api/Venue/space';
import { uploadPic } from '@/api/Upload/upload';
import CitySelect from '@/components/CitySelect/index.vue';
import SearchInput from '@/components/SearchInput/index.vue';
import QrcodeEdit_Dialog from './QrcodeEdit_Dialog.vue';

const props = defineProps({
  dialogModify: {
    type: Boolean,
  },
  ModifyRow: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['confirm', 'cancel']);
const formRef = ref(null);
const searchInputRef = ref(null);

// 表单数据 - 移到最前面
const form = ref({
  name: '',
  city: '',
  destName: '',
  province: '',
  destLongitude: '',
  destLatitude: '',
  coverUrl: '',
  floorPlanUrl: '',
  facilityIdList: [],
  mediaIdList: [],
  todayAnnouncement: '',
  intro: '',
  orderLevel: 1,
  state: '',
});

// 其他响应式数据
const qrcodeData = ref([]);
const qrcodeDialogVisible = ref(false);
const isEdit = ref(false);
const currentEditData = ref(null);
const newResponse = ref([]);
const addressBackup = ref({});
const facilitiesListAll = ref([]);
const videoListAll = ref([]);

const disabledInput = ref(true);
// 计算属性
const coordinates = computed(() => {
  if (form.value.destLongitude && form.value.destLatitude) {
    return `${form.value.destLongitude},${form.value.destLatitude}`;
  }
  return '';
});

// 添加加载状态
const loading = ref(false);

// 添加一个标记，用于控制是否允许搜索
const allowSearch = ref(false);

// 添加一个变量来存储城市选择的值
const cityValues = ref([]);

// 获取详情数据
const getDetails = async () => {
  if (!props.ModifyRow?.spaceId) return;

  try {
    const res = await getSpaceDetails(props.ModifyRow.spaceId);
    if (res.data.code === 200) {
      const detailData = res.data.data;

      // 处理基础数据
      form.value = {
        name: detailData.name || '',
        city: detailData.city || '',
        destName: detailData.destName || '',
        destLongitude: detailData.destLongitude || '',
        destLatitude: detailData.destLatitude || '',
        coverUrl: detailData.coverUrl || '',
        floorPlanUrl: detailData.floorPlanUrl || '',
        facilityIdList:
          detailData.facilityList?.map((item) => item.facilityId) || [],
        mediaIdList: detailData.mediaList?.map((item) => item.id) || [],
        todayAnnouncement: detailData.todayAnnouncement || '',
        intro: detailData.intro || '',
        orderLevel: detailData.orderLevel || 0,
        state: detailData.state ?? 0,
        province: detailData.province || '',
      };

      // 如果有城市数据，设置 cityValues 和 disabledInput
      if (detailData.city && detailData.province) {
        cityValues.value = [detailData.province, detailData.city];
        disabledInput.value = false;
      }

      // 处理二维码列表
      qrcodeData.value = Array.isArray(detailData.qrCodeList)
        ? detailData.qrCodeList
        : [];

      // 保存地址备份数据
      addressBackup.value = {
        title: detailData.name,
        address: detailData.destName,
        location: {
          lng: detailData.destLongitude,
          lat: detailData.destLatitude,
        },
      };
    }
  } catch (error) {
    console.error('获取详情数据失败:', error);
    throw error;
  }
};

// 初始化数据
const initData = async () => {
  try {
    const [facilitiesRes, videoRes] = await Promise.all([
      getFacilities(),
      getVideoList(),
    ]);

    facilitiesListAll.value = facilitiesRes.data.data || [];
    videoListAll.value = videoRes.data.data || [];
  } catch (error) {
    console.error('获取初始数据失败:', error);
  }
};

// 对话框打开时的处理
const handleDialogOpen = async () => {
  loading.value = true;
  try {
    allowSearch.value = false; // 初始化时不允许搜索
    await Promise.all([getDetails(), initData()]);
  } catch (error) {
    console.error('初始化数据失败:', error);
    ElMessage.error('初始化数据失败');
  } finally {
    loading.value = false;
  }
};

// 修改表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入空间名称', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!cityValues.value || cityValues.value.length !== 2) {
          callback(new Error('请先选择省份和城市'));
        } else if (!value) {
          callback(new Error('请输入空间名称'));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change'],
    },
  ],
  city: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!cityValues.value || cityValues.value.length !== 2) {
          callback(new Error('请选择省份和城市'));
        } else {
          callback();
        }
      },
      trigger: ['change', 'blur'],
    },
  ],
  destName: [{ required: true, message: '请选择空间地址', trigger: 'change' }],
  destLongitude: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.value.destLongitude || !form.value.destLatitude) {
          callback(new Error('请选择空间地址以获取坐标'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  coverUrl: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
  floorPlanUrl: [
    { required: true, message: '请上传空间平面图', trigger: 'change' },
  ],
  intro: [{ required: true, message: '请输入空间介绍', trigger: 'blur' }],
  orderLevel: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
  facilityIdList: [
    { required: true, message: '请选择设施', trigger: 'change' },
  ],
  mediaIdList: [{ required: true, message: '请选择视频', trigger: 'change' }],
  todayAnnouncement: [
    { required: true, message: '请输入活动公告', trigger: 'blur' },
  ],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// 修改保存处理函数
const handleConfirm = async () => {
  if (qrcodeData.value.length === 0) {
    ElMessage({
      message: '请至少添加一个二维码',
      type: 'warning',
    });
    return;
  }

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!cityValues.value || cityValues.value.length !== 2) {
        ElMessage.warning('请选择省份和城市');
        return;
      }
      try {
        const submitData = {
          ...form.value,
          qrCodeList: qrcodeData.value,
          addressBackup: JSON.stringify(addressBackup.value),
          spaceId: props.ModifyRow.spaceId,
        };

        const res = await modifySpace(submitData);
        if (res.data.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          });
          emit('confirm');
        } else {
          ElMessage({
            message: res.data.msg || '修改失败',
            type: 'error',
          });
        }
      } catch (error) {
        console.error('修改失败:', error);
        ElMessage({
          message: '修改失败',
          type: 'error',
        });
      }
    }
  });
};

const handleCancel = () => {
  emit('cancel');
};

const handleClose = () => {
  emit('cancel');
};

// 对话框关闭时的处理
const handleDialogClosed = () => {
  // 重置所有相关状态
  form.value = {
    name: '',
    city: '',
    destName: '',
    province: '',
    destLongitude: '',
    destLatitude: '',
    coverUrl: '',
    floorPlanUrl: '',
    facilityIdList: [],
    mediaIdList: [],
    todayAnnouncement: '',
    intro: '',
    orderLevel: 1,
    state: '',
  };
  cityValues.value = [];
  qrcodeData.value = [];
  addressBackup.value = {};
  disabledInput.value = true;
  allowSearch.value = false;
};

// 添加图片格式校验函数
const validateImageType = (file) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！');
    return false;
  }
  return true;
};

// 修改封面图片上传处理
const handleCoverChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.coverUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('coverUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 修改平面图上传处理
const handleFloorPlanChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.floorPlanUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('floorPlanUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 处理封面图片删除
const handleCoverRemove = () => {
  form.value.coverUrl = '';
};

// 处理平面图删除
const handleFloorRemove = () => {
  form.value.floorPlanUrl = '';
};

// 处理城市选择
const handleCityValue = (value) => {
  cityValues.value = value;
  if (value && value.length === 2) {
    disabledInput.value = false;
    // 选择完省市后，触发表单校验
    nextTick(() => {
      formRef.value?.validateField(['city', 'name']);
    });
  } else {
    disabledInput.value = true;
    // 清空相关字段
    form.value.name = '';
    form.value.destName = '';
    form.value.destLongitude = '';
    form.value.destLatitude = '';
    // 重置搜索输入框
    if (searchInputRef.value) {
      searchInputRef.value.clearSearch();
    }
  }
};

// 处理城市变更
const handleCityChange = (city) => {
  form.value.city = city;
  // 如果城市值为空，清空所有相关字段
  if (!city) {
    form.value.name = '';
    form.value.destName = '';
    form.value.destLongitude = '';
    form.value.destLatitude = '';
    disabledInput.value = true;
  }
  allowSearch.value = true;

  // 重置搜索输入框的状态
  if (searchInputRef.value) {
    searchInputRef.value.clearSearch();
  }

  // 触发城市字段的校验
  nextTick(() => {
    formRef.value?.validateField('city');
  });
};

// 搜索空间
const searchSpaces = async (keyword) => {
  // 如果不允许搜索或没有关键词，直接返回空数组
  if (!allowSearch.value || !keyword.trim()) {
    return [];
  }

  if (!form.value.city) {
    return [];
  }

  try {
    const response = await getAddress({
      keyword: keyword,
      region: form.value.city,
    });

    if (response.data.code === 200 && response.data.data.data) {
      return response.data.data.data.map((item) => ({
        id: item.id,
        title: item.title,
        address: item.address,
        location: item.location,
        lng: item.location?.lng,
        lat: item.location?.lat,
      }));
    }
    return [];
  } catch (error) {
    console.error('搜索空间失败:', error);
    return [];
  }
};

// 处理空间选择
const handleSpaceSelect = async (item) => {
  try {
    form.value.name = item.title;
    form.value.destName = item.address;
    form.value.destLongitude = item.location?.lng || item.lng;
    form.value.destLatitude = item.location?.lat || item.lat;
    addressBackup.value = item;

    await nextTick();
    await formRef.value?.validateField('name');
  } catch (error) {
    console.error('空间选择处理失败:', error);
  }
};

// 处理输入
const handleNameInput = () => {
  // 清空相关字段
  form.value.destName = '';
  form.value.destLongitude = '';
  form.value.destLatitude = '';
  formRef.value?.validateField('name');
  allowSearch.value = true; // 允许搜索
};

// 二维码相关处理函数
const handleAddQrcode = () => {
  isEdit.value = false;
  currentEditData.value = null;
  qrcodeDialogVisible.value = true;
};

const handleQrcodeEdit = (row) => {
  isEdit.value = true;
  currentEditData.value = row;
  qrcodeDialogVisible.value = true;
};

const handleQrcodeDelete = (row) => {
  ElMessageBox.confirm('确认删除该二维码信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const index = qrcodeData.value.findIndex((item) => item === row);
      if (index > -1) {
        qrcodeData.value.splice(index, 1);
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
      }
    })
    .catch(() => {});
};

const handleQrcodeConfirm = (data) => {
  if (isEdit.value && currentEditData.value) {
    const index = qrcodeData.value.findIndex(
      (item) => item === currentEditData.value
    );
    if (index > -1) {
      qrcodeData.value[index] = { ...data };
    }
  } else {
    qrcodeData.value.push({ ...data });
  }
  qrcodeDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.upload-box {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
  }

  .upload-placeholder {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: #8c8c8c;

    .el-icon {
      font-size: 20px;
      margin-bottom: 8px;
    }

    span {
      display: block;
      font-size: 12px;
    }
  }

  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
    border-bottom-left-radius: 8px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }

  &:hover .delete-icon {
    opacity: 1;
  }
}

.space-info-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .el-input {
    flex-shrink: 0;
  }

  .el-button {
    flex-shrink: 0;
    white-space: nowrap;
  }
}

:deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}

:deep(.custom-divider) {
  margin: 0;
  margin-bottom: 20px;
}

:deep(.el-dialog__header) {
  padding-bottom: 10px;
  margin-right: 0;
}

.qrcode-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.qrcode-header {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.qrcode-section {
  width: 100%;

  :deep(.el-table) {
    width: 100% !important;
  }
}
</style>
